﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System.Reflection;

namespace PmSoft.Core.Job;

/// <summary>
/// 作业执行包装器抽象类，负责创建作用域并调用作业定义
/// </summary>
public abstract class JobExecutionWrapper
{
	private readonly IServiceScopeFactory _scopeFactory;
	private readonly ILogger<JobExecutionWrapper> _logger;

	/// <summary>
	/// 构造函数，注入服务作用域工厂和日志记录器
	/// </summary>
	/// <param name="scopeFactory">服务作用域工厂，用于创建 Scope</param>
	/// <param name="logger">日志记录器</param>
	protected JobExecutionWrapper(IServiceScopeFactory scopeFactory, ILogger<JobExecutionWrapper> logger)
	{
		_scopeFactory = scopeFactory;
		_logger = logger;
	}

	/// <summary>
	/// 执行作业的通用逻辑，创建作用域并调用作业
	/// </summary>
	/// <param name="jobType">作业类型</param>
	protected async Task ExecuteJob(Type jobType)
	{
		try
		{
			using (var scope = _scopeFactory.CreateScope())
			{
				var jobInstance = scope.ServiceProvider.GetService(jobType) as IJobDefinition;
				if (jobInstance != null)
				{
					var jobName = jobType.GetCustomAttribute<JobScheduleAttribute>()?.Name ?? jobType.Name;
					_logger.LogInformation("开始执行作业 {JobName}", jobName);
					await jobInstance.Execute();
					_logger.LogInformation("作业 {JobName} 在 {ExecutionTime} 执行完成", jobName, DateTime.Now);
				}
				else
				{
					_logger.LogError("无法解析作业 {JobType} 的实例", jobType.Name);
				}
			}
		}
		catch (Exception ex)
		{
			_logger.LogError(ex, "作业 {JobType} 执行失败", jobType.Name);
		}
	}
}
